<!-- 考勤-考勤管理-班次管理 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        :title="title"
        :breadCrumb="breadCrumb"
        showBack
      ></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space>
          <div>班次类型：</div>
          <a-select v-model="type" @change="refresh">
            <a-option :value="0">全部</a-option>
            <a-option :value="1">单班次</a-option>
            <a-option :value="2">两班次</a-option>
            <a-option :value="3">三班次</a-option>
            <a-option :value="4">多班次</a-option>
          </a-select>
        </a-space>
        <a-input-search
          :style="{ width: '220px' }"
          placeholder="请输入考勤组名称"
          search-button
          @search="onSearch"
          @press-enter="onSearch"
          v-model="nameSearch"
        />
      </template>
      <template #right>
        <a-button type="primary" @click="add" style="margin-right: 10px">
          新增班次
        </a-button>
        <a-button type="primary" @click="dels" style="margin-right: 10px">
          批量删除
        </a-button>
      </template>
    </ConditionBox>
    <table-turn
      :table-data="getTableData"
      ref="tableRef"
      :args="{
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false
        }
      }"
    >
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="name" title="班次名称">
      </a-table-column>
      <a-table-column :width="200" data-index="definition" title="班次简称">
        <template #cell="{ record }">
          <template v-if="record.type === 1">
            {{ record?.attendanceClassesSetting[0]?.shortName || '暂无' }}
          </template>
          <template v-else>{{ record?.shortName || '' }} </template>
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="type" title="班次分类">
        <template #cell="{ record }">
          {{ classes[record.type - 1] }}
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="definition" title="出勤时间">
        <template #cell="{ record }">
          <template v-if="record.type === 1">
            <div style="padding: 0 10px">
              {{
                record?.attendanceClassesSetting[0].commutingTime
                  .map((ele: any) => attendanceTime(ele))
                  .join(';')
              }}
            </div>
          </template>
          <template v-else>
            <div style="padding: 0 10px">
              {{
                record.type
                  ? null
                  : record.commutingTime
                      .map((ele: any) => attendanceTime(ele))
                      .join(';')
              }}
            </div>
          </template>
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="definition" title="每天出勤时长">
        <template #cell="{ record }">
          <template v-if="record.type === 1">
            {{ allTime(record?.attendanceClassesSetting[0]) }}
          </template>
          <template v-else>
            {{ record.type ? null : allTime(record) }}
          </template>
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="definition" title="计出勤天数">
        <template #cell="{ record }">
          <template v-if="record.type === 1"> 1 </template>
          <template v-else>{{ record.type ? null : 1 }}</template>
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="definition" title="班次负责人">
        <template #cell="{ record }">
          <template v-if="record?.userInfo">
            {{ record?.userInfo?.map(({ name }: any) => name).join('、') }}
          </template>
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="" title="操作" fixed="right">
        <template #cell="{ record }">
          <a-tooltip content="编辑">
            <IconFont
              type="icon-edit"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
              @click="goEdit(record)"
            />
          </a-tooltip>
          <a-tooltip content="删除" position="left">
            <a-popconfirm content="是否确认删除该条数据?" @ok="del(record.id)">
              <icon-font
                type="icon-delete"
                :size="26"
                :style="{
                  cursor: 'pointer',
                  marginRight: '10px'
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </template>
      </a-table-column>
    </table-turn>
  </ContentCard>
</template>

<script lang="ts" setup>
import {
  GetClassesManage,
  DelClassesManage
} from '@/apis/attendance/base-setting/index';
import { Message, Modal } from '@arco-design/web-vue';

const title = '班次管理';
const router = useRouter();
const breadCrumb: string[] = ['考勤', '考勤管理', '班次管理'];
const classes = ['单班次', '两班次', '三班次', '多班次'];
const type = ref(0);
let tableRef = ref();
let nameSearch = ref(''); // 搜索框值

// 新增
const add = () => {
  // modalVisible.value = true;
  router.push({
    name: 'AttendanceManagementClassSettingAdd'
  });
};
function calculateHourDifference(startTime: string, endTime: string) {
  const start = +new Date(`2000-01-01 ${startTime}`);
  const end = +new Date(`2000-01-01 ${endTime}`);
  const hourDifference = Math.abs(end - start) / 36e5; // 36e5 是一个小时的毫秒数
  return hourDifference;
}
const allTime = (data: any) => {
  let num = 0;
  data.commutingTime.forEach((ele: any) => {
    num += calculateHourDifference(
      ele.workingTime || '00:00',
      ele.afterWorkTime || '00:00'
    );
    num -= calculateHourDifference(
      ele.restTimeStart || '00:00',
      ele.restTimeEnd || '00:00'
    );
  });
  return num;
};

[12, 23, 2, 4].forEach((ele) => {
  try {
    if (ele === 2) {
      throw new Error('1111');
    }
    console.log(ele);
  } catch (error) {
    console.log(error);
  }
});
const array = [1, 2, 3, 4, 5];
let k = 0;
while (k < array.length) {
  if (array[k] === 3) {
    break; // 当元素为3时跳出循环
  }

  console.log('k', array[k]);
  k++;
}

let arr = [1, 2, 3, 4, 45, 5];
arr.forEach((e, i, a) => {
  i === 3 && (arr.length = 1);
  console.log('[ e ] >', e, arr, a);
}, 1);

const attendanceTime = (data: any) => {
  return (
    '上下班：' +
    data.workingTime +
    '-' +
    data.afterWorkTime +
    ',' +
    '休息：' +
    data.restTimeStart +
    '-' +
    data.restTimeEnd
  );
};

// 获取表格数据
const getTableData = async (data: any) => {
  try {
    const res = await GetClassesManage({
      type: type.value && type.value,
      ...data,
      name: nameSearch.value
    });
    res.content.forEach((ele: any) => {
      if (ele.type !== 1) {
        ele.children = ele.attendanceClassesSetting;
      }
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);

const dels = () => {
  if (selectedList.value.length === 0) {
    Message.error('请至少选择一项！');
  } else {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的数据吗？',
      onOk: async () => {
        try {
          await DelClassesManage({
            ids: selectedList.value
          });
          tableRef.value.selectedList = [];
          tableRef.value.loadData();
        } catch (error: unknown) {
          console.log(error);
        }
      }
    });
  }
};

// 搜索框搜索事件
const onSearch = () => {
  refresh();
};

// 编辑
const goEdit = (record: any) => {
  localStorage.setItem('classSetting', JSON.stringify(record));
  router.push({
    name: 'AttendanceManagementClassSettingAdd'
  });
};

// 删除某一行
const del = async (id: number) => {
  try {
    await DelClassesManage({ ids: [id] });
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 刷新表格数据
const refresh = () => {
  tableRef.value.loadData();
};
</script>

<style lang="less" scoped>
.tag {
  height: 48px;
  color: #000;
  background-color: rgba(61, 126, 255, 1);
  width: 100%;
  font-size: 15px;
}

:deep(.arco-collapse-item-content) {
  background-color: #fff;
}
</style>
